package view
{
	import flash.events.Event;
	import flash.system.System;
	import flash.text.TextField;
	import flash.utils.getTimer;
	import view.micro.IMicroSprite;
	
	/**
	 * Displays the current framerate.
	 */
	public class FrameRateCounter extends TextField implements IMicroSprite
	{
		
		private var last_time:int;
		private var avg:Number;
		
		/**
		 * Create a new frame rate counter.
		 */
		public function FrameRateCounter()
		{
			last_time = getTimer();
			addEventListener(Event.ADDED_TO_STAGE, init);
			mouseEnabled = false;
			
			height = 20;
		}
		
		/**
		 * Called when added to the stage.
		 * @param	e
		 */
		private function init(e:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			addEventListener(Event.ENTER_FRAME, onFrameEnter);
			avg = stage.frameRate;
			text = String(avg);
		}
		
		/**
		 * Handler for the frame enter event to update automatically.
		 * @param	e
		 */
		private function onFrameEnter(e:Event):void 
		{
			update();
		}
		
		/**
		 * Call every frame.
		 */
		public function update():void
		{
			var current_time:int = getTimer();
			avg = (0.9 * avg) + (0.1 * int(1000.0 / (current_time - last_time)));
			text = "fps: " + Math.round(avg) + " " + int(System.totalMemory / (1024 * 1024)) + " Mb";
			last_time = current_time;
		}
		
		public function readyToRemove():Boolean
		{
			return false;
		}
	
	}

}